package com.example.obmb.common.base;

import com.fasterxml.jackson.annotation.JsonInclude;

import lombok.Data;

import java.io.Serializable;

/**
 * @Author qiuhongyu
 * @Date 2024/10/22 10:41
 * 统一响应格式
 */

@Data
@JsonInclude(JsonInclude.Include.NON_NULL)
public class R<T> implements Serializable {

    private static final long serialVersionUID = 7335980115088181776L;

    /**
     * 响应码
     */
    private int code;

    /**
     * 内容
     */
    private String msg;

    /**
     * 返回数据
     */
    private T data;

    public R() {
    }

    public R(int code, String msg) {
        this.code = code;
        this.msg = msg;
    }

    public R(int code, String msg, T data) {
        this.code = code;
        this.msg = msg;
        this.data = data;
    }

    public R(int code, T data, String msg) {
        this.code = code;
        this.msg = msg;
        this.data = data;
    }

    public static <T> R<T> success() {
        return new R<>(ResponseCode.SUCCESS.getCode(), ResponseCode.SUCCESS.getMsg_EN());
    }

    public static <T> R<T> success(T data) {
        return new R<>(ResponseCode.SUCCESS.getCode(), ResponseCode.SUCCESS.getMsg_EN(), data);
    }

    public static <T> R<T> responseSuccess(Integer code, String msg, T data) {
        return new R<>(code, msg, data);
    }

    public static <T> R<T> getResponse(ResponseCode responseCode, T data) {

        return R.responseSuccess(
                responseCode.getCode(),
                responseCode.getMsg_CN(),
                data);
    }

    public static <E> R<E> result(int code, E data, String msg) {
        return new R<>(code, data, msg);
    }

    /**
     * 自动判断返回成功或失败
     *
     * @return Result
     */
    public boolean isSuccess() {
        return this.code == ResponseCode.SUCCESS.getCode();
    }
}
